#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/10/31 13:43
# @Author : 闫峰
# @File    : syc_promotion.py
import os
import time

from common.setting import ensure_path_sep
from third_services.allegro.RebatyesAndPromotions.offerdetails import OfferDetails
from third_services.allegro.RebatyesAndPromotions.rebatesAndPromotions import RebatesAndPromotions
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database
from utils.noticeUtils.dingtalkControl import DingTalkSendMsg
from concurrent.futures import ThreadPoolExecutor, wait, as_completed
from functools import partial

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])


def remove_file(info_path):
    if os.path.exists(info_path):
        os.remove(info_path)
    else:
        print(f"{info_path} 不存在")


info_path = ensure_path_sep(f"\\logs\\info-{dis_path}{time.time()}")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}{time.time()}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}{time.time()}.log")
remove_file(info_path)
remove_file(error_path)
remove_file(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')

global_str = []
count = 0


class TestPromotion:
    """
    同时allegro 促销活动
    """

    def atest_syc_promotion(self, source_id):
        api = RebatesAndPromotions()
        zhcxkj_center_listing_comprehensive = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"),
                                                       "zhcxkj_center_listing_comprehensive")
        test_zhcxkj_center_promotion = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        # MULTIPACK（同品折扣）
        offset = 0
        expect_data = []
        while True:
            if offset > 49950:
                break
            res = api.get_sale_loyalty_promotions(source_id, offset, "MULTIPACK", 50)
            handler_list = list(
                map(lambda x: (
                x.get('id'),
                2 if x.get('status') == 'INACTIVE' else (1 if x.get('status') == 'ACTIVE' else 3),
                int(x.get('offerCriteria')[0].get('offers')[0].get('id'))
                ),
                res.get('promotions'))
            )
            self.check_data(handler_list, source_id, 0)
            # expect_data += handler_list

            if offset == 0:
                promotion_count = res.get('totalCount')
                INFO.logger.info(f"source_id={source_id} MULTIPACK（同品折扣）活动数{promotion_count}个")
            offset += 5000
        self.check_data(expect_data, source_id, 0)

    def check_data(self, expect_data, source_id, promotion_type):
        test_zhcxkj_center_promotion = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        get_actual_data = """
        SELECT promotion_id,`status`,offer_id 
        FROM test_zhcxkj_center_promotion.t_allegro_promotion 
        WHERE source_id=%s 
        AND promotion_type=%s;
        """
        actual_data = test_zhcxkj_center_promotion.fetch_all_tuple(get_actual_data, (source_id, promotion_type))
        # 判断预期的的集合A的数据 全部都在实际的集合B中
        if set(expect_data).issubset(set(actual_data)):
            pass
        else:
            print(f"没有同步到数据如下{set(expect_data) - set(actual_data)}")

    # 同步 CROSS_MULTIPACK （不同品集合折扣）
    def atest_syc_promotion_CROSS_MULTIPACK(self, source_id):
        api = RebatesAndPromotions()
        zhcxkj_center_listing_comprehensive = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"),
                                                       "zhcxkj_center_listing_comprehensive")
        test_zhcxkj_center_promotion = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        # MULTIPACK（同品折扣）
        offset = 0
        expect_data = []
        while True:
            if offset > 49950:
                break
            res = api.get_sale_loyalty_promotions(source_id, offset, "MULTIPACK", 50)

            handler_list = list(

                map(lambda x: (
                x.get('id'),
                2 if x.get('status') == 'INACTIVE' else (1 if x.get('status') == 'ACTIVE' else 3),
                list(map(lambda x: int(x['id']),x.get('offerCriteria')[0].get('offers')))
                ),
                res.get('promotions'))
            )

            self.check_data_cross_multipack(handler_list, source_id, 1)
            # expect_data += handler_list

            if offset == 0:
                promotion_count = res.get('totalCount')
                INFO.logger.info(f"source_id={source_id} MULTIPACK（同品折扣）活动数{promotion_count}个")
            offset += 5000

    def check_data_cross_multipack(self, handler_list, source_id, param):
        test_zhcxkj_center_promotion = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        check_list = []
        for data in handler_list:
            for offer in data[2]:
                check_list.append((data[0],data[1],offer))
        check_sql = """
        SELECT promotion_id,`status`,offer_id FROM test_zhcxkj_center_promotion.t_allegro_promotion
        WHERE source_id=%s
        AND promotion_type=%s
        """
        actual_data = test_zhcxkj_center_promotion.fetch_all_tuple(check_sql,(source_id,param))
        expect_data_set = set(check_list)
        actucl_data_set = set(actual_data)

        # 判断预期的的集合A的数据 全部都在实际的集合B中
        if expect_data_set.issubset(actucl_data_set):
            pass
        else:
            print(f"没有同步到数据如下{expect_data_set - actucl_data_set}")


if __name__ == '__main__':
    net_db = Database(ensure_path_sep("\\testcases\\Intelligent_publishing\\sku_category\\config.yaml"),
                      "znkd_database_prod")
    get_source_id_list = """
    SELECT a.OrderSourceId FROM sys_ordersource a 
    LEFT JOIN sys_ordersource_authorization b ON a.CustomerId=b.CustomerId AND a.OrderSourceId=b.OrderSourceId
    WHERE 
    a.OrderSourceType =67
    AND a.IsActive=1 AND a.IsDelete=0 AND b.IsActive=1
    """
    # source_id_list = net_db.fetch_all_tuple(get_source_id_list, ())
    #
    # source_id_list = list(map(lambda x: x[0], source_id_list))
    # ordersource_id_res = []
    # api = RebatesAndPromotions()
    # for source_id in source_id_list:
    #
    #     res = api.get_sale_loyalty_promotions(source_id, 0, "MULTIPACK", 50)
    #     if res:
    #         promotion_count = res.get('totalCount')
    #         ordersource_id_res.append((source_id, promotion_count))
    #     else:
    #         continue
    # print(ordersource_id_res)
    a = [(9058, 125384), (9059, 109272), (9062, 130122), (9046, 323218), (10190, 0), (10205, 105671), (10206, 100483), (10207, 49545), (10242, 142728), (10267, 126801), (10400, 102975), (10401, 122945), (10402, 81979), (10724, 97431), (10797, 43), (10998, 81674), (11005, 89554), (11006, 38677), (11007, 108353), (11029, 153585), (11081, 73714), (11082, 66971), (11273, 77311), (11333, 121582), (11373, 1), (11402, 73871), (11412, 75996), (11929, 125201), (11930, 86717), (11931, 49578), (11940, 3), (11995, 155421), (12032, 63302), (12033, 142406), (12034, 91728), (12035, 122129), (12036, 52103), (12083, 100709), (12084, 100616), (12086, 0), (12208, 91190), (12209, 0), (12210, 0), (12211, 116794), (12212, 62763), (12213, 132031), (12214, 141585), (12226, 87603), (12228, 2), (12238, 89230), (12239, 140445), (12498, 0), (12499, 56843), (12500, 46385), (12501, 0), (12502, 139628), (12531, 139217), (12532, 104866), (12567, 145339), (12568, 80566), (12569, 99996), (12570, 72768), (12574, 119671), (13015, 87526), (13031, 111761), (13032, 44505), (13198, 80587), (13433, 65063), (13434, 175923), (13438, 104817), (13442, 63755), (10783, 45), (13630, 2), (13631, 144854), (13647, 82420), (13961, 156298), (13962, 3), (13972, 124256), (13973, 143900), (13974, 120727), (14077, 118777), (14078, 120066), (14079, 106828), (14080, 132243), (14081, 81068), (14376, 136462), (14377, 100735), (14378, 123336), (14379, 139663), (14400, 89426), (14401, 223536), (14410, 71216), (14420, 84687), (14421, 99139), (14450, 9914), (14451, 78148), (14514, 127066), (14515, 107944), (14516, 96035), (14517, 128710), (14540, 128226), (14541, 53727), (14547, 45441), (14549, 133087), (16455, 78550), (16668, 107406), (17161, 107490), (17183, 52178), (17184, 100180), (17402, 0), (17655, 89393), (18028, 127473), (18029, 21679), (18030, 110215), (18031, 81634), (18032, 116606), (18189, 106216), (18205, 96925), (18206, 65775), (18208, 74410), (18348, 85793), (18349, 81106), (18350, 0), (18351, 0), (19228, 79164), (19229, 75572), (19230, 63413), (19231, 118264), (19232, 93526), (19233, 57436), (19234, 53535), (19235, 60841), (19236, 88550), (19251, 99230), (19360, 102856), (19361, 133656), (19362, 86898), (19364, 175714), (19387, 45241), (19388, 102427), (19389, 83023), (19390, 100499), (19391, 112301), (19509, 94337), (19510, 95291), (19512, 29786), (19513, 177184), (19653, 104233), (19654, 85595), (19655, 120599), (19656, 128119), (19657, 53112), (19853, 140223), (19890, 124779), (19891, 70545), (19892, 90364), (19893, 67000), (19984, 42), (19987, 0), (19986, 60), (20004, 0), (20006, 95), (20298, 85981), (20317, 79981), (20318, 90614), (20319, 72426), (20320, 44586), (20321, 61931), (20322, 58421), (20323, 84372), (20324, 94371), (20327, 0), (20328, 0), (20330, 68434), (20344, 8272), (20345, 58583), (20346, 5), (20355, 65302), (20356, 61950), (20357, 61374), (20359, 82328), (20360, 85974), (20361, 82887), (20362, 45082), (20363, 55369), (20370, 107643), (20371, 109049), (20372, 0), (20373, 39204), (20391, 39478), (20392, 109674), (20393, 29734), (20394, 49269), (20415, 0), (20416, 1), (20417, 0), (20418, 0), (20421, 62661), (20422, 50668), (20423, 80635), (20424, 94653), (20441, 37839), (20442, 1), (20443, 0), (20444, 0), (20445, 45039), (20446, 10560), (20447, 47411), (20448, 47844), (20539, 1), (20541, 2), (20540, 17854), (20547, 0), (20549, 1), (20548, 18415), (20557, 0), (20558, 0), (20559, 0), (20560, 0), (20607, 0)]

    b = sorted(a,key=lambda x:x[1],reverse=True)
    print(b)